package cn.edkuir.seckill.service.impl;

import cn.edkuir.common.to.mq.SeckillOrderTo;
import cn.edkuir.common.utils.R;
import cn.edkuir.common.vo.MemberRespVo;
import cn.edkuir.seckill.feign.CouponFeignService;
import cn.edkuir.seckill.feign.ProductFeignService;
import cn.edkuir.seckill.interceptor.LoginUserInterceptor;
import cn.edkuir.seckill.service.SeckillService;
import cn.edkuir.seckill.to.SeckillRedisTo;
import cn.edkuir.seckill.vo.SeckillSessionsWithSkusVo;
import cn.edkuir.seckill.vo.SeckillSkuVo;
import cn.edkuir.seckill.vo.SkuInfoVo;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import sun.misc.Unsafe;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";   //+ 开始时间_结束时间

    private final String SKUS_CACHE_PREFIX = "seckill:skus";    //商品id作为hash key

    private final String SKUS_STOCK_SEMAPHORE = "seckill:stock:";   //+ 商品随机码


    @Override
    public void uploadSeckillSku() {
        //扫描最近三天需要参与秒杀的活动
        R r = couponFeignService.getLasted3DaysSession();
        if(r.getCode() == 0) {
            List<SeckillSessionsWithSkusVo> data = r.getData(new TypeReference<List<SeckillSessionsWithSkusVo>>() {
            });

            //缓存到redis
            //1.缓存活动信息
            saveSessionInfo(data);

            //2.缓存活动关联的商品信息
            saveSessionSkusInfo(data);
        }
    }


    //获取当前时间可以参与的所有秒杀商品
    @Override
    public List<SeckillRedisTo> getCurrentSeckillSkus() {
        List<SeckillRedisTo> total = new ArrayList<>();

        //TODO 自定义受保护的资源
        try(Entry entry = SphU.entry("seckillSkus")) {
            //1.确定当前时间属于哪个秒杀场次
            long currentTime = new Date().getTime();
            Set<String> keys = stringRedisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
            if(keys == null) {
                return null;
            }
            for (String key : keys) {
                //seckill:sessions:1628662800000_1628666383000
                String[] s = key.replace(SESSIONS_CACHE_PREFIX, "").split("_");
                long start = Long.parseLong(s[0]);
                long end = Long.parseLong(s[1]);
                if(currentTime >= start && currentTime <= end) {
                    //在当前场次时间范围内
                    //2.获取当前场次的所有商品信息
                    //当前场次的所有skuId
                    List<String> ids = stringRedisTemplate.opsForList().range(key, 0, -1);
                    if(ids == null) {
                        break;
                    }
                    BoundHashOperations<String, String, String> operations = stringRedisTemplate.boundHashOps(SKUS_CACHE_PREFIX);
                    //根据skuId查询商品详情
                    List<String> skus = operations.multiGet(ids);
                    if(!CollectionUtils.isEmpty(skus)) {
                        List<SeckillRedisTo> seckillRedisTos = skus.stream().map(sku
                                -> JSON.parseObject(sku, SeckillRedisTo.class)).collect(Collectors.toList());
                        total.addAll(seckillRedisTos);
                    }
                }
            }
        } catch (BlockException e) {
            log.error("资源被限流, {}", e.getMessage());
        }

        return total;
    }


    //根据skuId获取某一个商品的秒杀信息
    @Override
    @SentinelResource(value = "seckillSkuInfo", blockHandler = "getSeckillSkuInfoBlockHandler")
    public SeckillRedisTo getSeckillSkuInfo(Long skuId) {
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SKUS_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        //正则表达式
        String regx = "\\d_" + skuId;
        if(!CollectionUtils.isEmpty(keys)) {
            for (String key : keys) {
                //5_10
                if(Pattern.matches(regx, key)) {
                    String s = hashOps.get(key);
                    SeckillRedisTo seckillRedisTo = JSON.parseObject(s, SeckillRedisTo.class);
                    //秒杀还未开始, 去掉随机码
                    Long startTime = seckillRedisTo.getStartTime();
                    Long currentTime = new Date().getTime();
                    if(currentTime < startTime) {
                        seckillRedisTo.setRandomCode(null);
                    }

                    return seckillRedisTo;
                }
            }
        }
        return null;
    }

    public SeckillRedisTo getSeckillSkuInfoBlockHandler(Long skuId, BlockException e) {
        log.error("原方法getSeckillSkuInfo被降级, {}", e.getMessage());
        return null;
    }


    //秒杀
    @Override
    public String kill(String killId, String key, Integer num) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        //1.获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SKUS_CACHE_PREFIX);
        String json = hashOps.get(killId);
        if(StringUtils.isEmpty(json)) {
            return null;
        }
        SeckillRedisTo seckillRedisTo = JSON.parseObject(json, SeckillRedisTo.class);

        //2.校验合法性
        //校验时间
        Long startTime = seckillRedisTo.getStartTime();
        Long endTime = seckillRedisTo.getEndTime();
        long currentTime = new Date().getTime();
        long ttl = endTime - currentTime;
        if(currentTime < startTime || currentTime > endTime) {
            return null;
        }
        //校验随机码和商品id
        String randomCode = seckillRedisTo.getRandomCode();
        String id = seckillRedisTo.getPromotionSessionId() + "_" + seckillRedisTo.getSkuId();
        if(!randomCode.equals(key) || !killId.equals(id)) {
            return null;
        }
        //校验购物数量是否合理
        Integer limit = seckillRedisTo.getSeckillLimit();
        if(num > limit) {
            return null;
        }
        //验证这个人是否已经购买过了, 幂等性:只要秒杀成功就去redis占位  userId_sessionId_skuId
        String redisKey = memberRespVo.getId() + "_" + id;
        //当前场次一结束就自动过期
        Boolean hasBuy = stringRedisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
        if(!hasBuy) {
            //该用户已经参与过秒杀
            return null;
        }

        //3.秒杀, 获取信号量
        RSemaphore semaphore = redissonClient.getSemaphore(SKUS_STOCK_SEMAPHORE + randomCode);
        boolean res = semaphore.tryAcquire(num);
        if(res) {
            //秒杀成功, 返回订单号, 并发送给MQ, 订单服务监听, 生成订单
            String orderSn = IdWorker.getTimeId();
            SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
            seckillOrderTo.setOrderSn(orderSn);
            seckillOrderTo.setNum(num);
            seckillOrderTo.setMemberId(memberRespVo.getId());
            seckillOrderTo.setPromotionSessionId(seckillRedisTo.getPromotionSessionId());
            seckillOrderTo.setSeckillPrice(seckillRedisTo.getSeckillPrice());
            seckillOrderTo.setSkuId(seckillRedisTo.getSkuId());
            rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", seckillOrderTo);
            return orderSn;
        }

        return null;
    }


    private void saveSessionInfo(List<SeckillSessionsWithSkusVo> sessions) {
        if(sessions == null) {
            return;
        }
        sessions.forEach(session -> {
            long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();
            String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
            if(!stringRedisTemplate.hasKey(key)) {
                List<String> ids = session.getRelationSkus().stream().map(sku ->
                        sku.getPromotionSessionId().toString() + "_" + sku.getSkuId().toString()).collect(Collectors.toList());
                //缓存活动信息
                stringRedisTemplate.opsForList().leftPushAll(key, ids);
            }
        });
    }


    private void saveSessionSkusInfo(List<SeckillSessionsWithSkusVo> sessions) {
        if(sessions == null) {
            return;
        }
        BoundHashOperations<String, Object, Object> operations = stringRedisTemplate.boundHashOps(SKUS_CACHE_PREFIX);
        sessions.forEach(session -> {
            session.getRelationSkus().forEach(seckillSkuVo -> {
                SeckillRedisTo seckillRedisTo = new SeckillRedisTo();
                //生成随机码
                String token = UUID.randomUUID().toString().replace("-", "");
                String key = seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString();

                if(!operations.hasKey(key)) {
                    //1.sku基本数据
                    R r = productFeignService.skuInfo(seckillSkuVo.getSkuId());
                    if(r.getCode() == 0) {
                        SkuInfoVo skuInfoVo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        seckillRedisTo.setSkuInfo(skuInfoVo);
                    }

                    //2.sku秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo, seckillRedisTo);

                    //3.秒杀时间信息
                    seckillRedisTo.setStartTime(session.getStartTime().getTime());
                    seckillRedisTo.setEndTime(session.getEndTime().getTime());

                    //4.随机码
                    seckillRedisTo.setRandomCode(token);

                    //5.准备分布式信号量  限流
                    //如果当前这个场次的商品库存信息已经上架就不需要上架了
                    RSemaphore semaphore = redissonClient.getSemaphore(SKUS_STOCK_SEMAPHORE + token);
                    //商品可以秒杀的数量作为信号量
                    semaphore.trySetPermits(seckillRedisTo.getSeckillCount());

                    operations.put(key, JSON.toJSONString(seckillRedisTo));
                }
            });
        });
    }
}
